Incorrect Array Copy (IAC)

Description:

IAC checks the semantics of the array copy library method (System.Array.Copy()). The audit detects for the possibility of incorrectly swapping argument positions. The order of copying array method arguments (source and destination) is unnatural (especially for C programmers who are familiar with the memcpy() function): unlike assignment operations, the source is specified before the destination. Usually, the copy array method is used to copy data from an existing array to a newly-created one. Generally, it does not make sense to copy data from an array that has just been created. This audit detects situations when the source argument refers to the array that was created just before the array copy.

Incorrect:

  Buffer = class
    strict private
    buf: array of integer;
    used:integer;
    public
      procedure Extend(size: integer);
  end;
...
procedure Buffer.Extend(size: integer);
var newSize: integer;
newBuf: array of integer;
begin
  if used + size > High(buf) then
  begin
    if used + size > used * 2 then
      newSize := used + size
    else
      newSize := used * 2;
    SetLength(newBuf,newSize);
    System.Array.Copy(newBuf, buf, used);
    buf := newBuf;
  end;
  used := used + size;
end;

Correct:

  Buffer = class
    strict private
    buf: array of integer;
    used:integer;
    public
      procedure Extend(size: integer);
  end;
...
procedure Buffer.Extend(size: integer);
var newSize: integer;
newBuf: array of integer;
begin
  if used + size > High(buf) then
  begin
    if used + size > used * 2 then
      newSize := used + size
    else
      newSize := used * 2;
    SetLength(newBuf,newSize);
    System.Array.Copy(buf, newBuf, used);
    buf := newBuf;
  end;
  used := used + size;
end;